package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.DimDrivageFace;
import net.hn.hnms.biz.plan.domain.PlanDrivage;
import net.hn.hnms.biz.plan.mapper.DimDrivageFaceMapper;
import net.hn.hnms.biz.plan.mapper.PlanDrivageMapper;
import net.hn.hnms.biz.plan.request.PlanDrivageReq;
import net.hn.hnms.biz.plan.service.IPlanDrivageService;
import net.hn.hnms.biz.plan.vo.PlanDrivageVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhaoyang
 * 掘进计划管理服务层实现
 * @date 2022-08-01
 */

@Service
@DS("master")
public class PlanDrivageServiceImpl extends BaseService<PlanDrivage, PlanDrivageVO> implements IPlanDrivageService {

    private PlanDrivageMapper planDrivageMapper;

    private DimDrivageFaceMapper dimDrivageFaceMapper;
    @Autowired
    private RemoteUserService remoteUserService;

    public PlanDrivageServiceImpl(PlanDrivageMapper planDrivageMapper, DimDrivageFaceMapper dimDrivageFaceMapper) {
        this.planDrivageMapper = planDrivageMapper;
        this.dimDrivageFaceMapper = dimDrivageFaceMapper;
    }

    /**
     *
     * @param planDrivage
     * @param pageQuery
     *
     * 查询掘进计划列表
     */
    @Override
    public ResponsePage<PlanDrivageVO> selectPageList(PlanDrivageReq planDrivage, PageQuery pageQuery) {

        Page<PlanDrivage> page = planDrivageMapper.selectPage(pageQuery.build(), buildQuery(planDrivage).orderByDesc(PlanDrivage::getDrivagePlanCode).orderByDesc(PlanDrivage::getCreateTime));
        List<PlanDrivageVO> list = page.getRecords().stream().map(o -> convert(o, PlanDrivageVO.class, o.getDrivagePlanType())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(list)) {
            DynamicDataSourceContextHolder.push("slave");
            Map<String, String> faces = dimDrivageFaceMapper.selectList(new LambdaQueryWrapper<DimDrivageFace>().eq(StrUtil.isNotBlank(planDrivage.getMineCode()), DimDrivageFace::getMineCode, planDrivage.getMineCode()))
                    .stream().collect(Collectors.toMap(DimDrivageFace::getDrivageFaceId, DimDrivageFace::getDrivageFaceName));
            DynamicDataSourceContextHolder.clear();
            for (PlanDrivageVO planDrivageVO : list) {
                planDrivageVO.setDrivageFaceName(faces.get(planDrivageVO.getDrivageFaceId()));
                LoginUser userInfoById = remoteUserService.getUserInfoById(Long.valueOf(planDrivageVO.getCreateUserId()));
                if (Optional.ofNullable(userInfoById).isPresent()) {
                    planDrivageVO.setCreateUserName(userInfoById.getNickname());
                }

            }
        }
        return new ResponsePage<>(list, page.getTotal());
    }

    /**
     * 构造查询条件
     * @param req
     * @return LambdaQueryWrapper<PlanDevelopment> 查询条件
     */
    private LambdaQueryWrapper<PlanDrivage> buildQuery(PlanDrivageReq req){
        LambdaQueryWrapper<PlanDrivage> lqw = new LambdaQueryWrapper<PlanDrivage>()
                .like(StrUtil.isNotBlank(req.getDrivagePlanCode()), PlanDrivage::getDrivagePlanCode, req.getDrivagePlanCode())
                .like(StrUtil.isNotBlank(req.getDrivagePlanName()), PlanDrivage::getDrivagePlanName, req.getDrivagePlanName())
                .eq(StrUtil.isNotBlank(req.getDrivagePlanType()), PlanDrivage::getDrivagePlanType, req.getDrivagePlanType())
                .eq(StrUtil.isNotBlank(req.getMineCode()), PlanDrivage::getMineCode, req.getMineCode())
                .eq(StrUtil.isNotBlank(req.getStatus()), PlanDrivage::getStatus, req.getStatus())
                .and(o->o.eq(req.getMineCode()!=null, PlanDrivage::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, PlanDrivage::getCompanyCode, req.getCompanyCode()));

        return lqw;
    }

    /**
     *
     * @param planDrivage
     * 查询掘进计划列表
     */
    @Override
    public List<PlanDrivageVO> selectList(PlanDrivageReq planDrivage) {
        List<PlanDrivage> list = planDrivageMapper.selectList(buildQuery(planDrivage));
        return list.stream().map(o -> convert(o, PlanDrivageVO.class, o.getDrivagePlanType())).collect(Collectors.toList());
    }

    /**
     *
     * @param planDrivage
     * 新增掘进计划
     */
    @Override
    public void insert(PlanDrivageReq planDrivage) {
        PlanDrivage insertObj = new PlanDrivage();
        copyProperties(planDrivage, insertObj, planDrivage.getDrivagePlanType());
        //自动生成 计划名称 计划编号
        if(planDrivage.getDrivagePlanType().equals("3")){
            insertObj.setDrivagePlanName(generatePlanName(planDrivage.getDrivagePlanType(),insertObj.getWeekTimeStart()));
            insertObj.setDrivagePlanCode(generatePlanCode(planDrivage.getDrivagePlanType(),insertObj.getWeekTimeStart()));
            insertObj.setPlanStartDate(insertObj.getWeekTimeStart());
            insertObj.setPlanEndDate(insertObj.getWeekTimeEnd());
        }else{
            insertObj.setDrivagePlanName(generatePlanName(planDrivage.getDrivagePlanType(),insertObj.getPlanStartDate()));
            insertObj.setDrivagePlanCode(generatePlanCode(planDrivage.getDrivagePlanType(),insertObj.getPlanStartDate()));
        }
        insertObj.setStatus("0");
        QueryWrapper<PlanDrivage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("drivage_plan_code", insertObj.getDrivagePlanCode());
        queryWrapper.eq("drivage_face_id", insertObj.getDrivageFaceId());
        if (planDrivageMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一工作面和同一时段的计划");
        }
        planDrivageMapper.insert(insertObj);
    }

    /**
     *
     * @param idList
     * 批量删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        planDrivageMapper.deleteBatchIds(idList);
    }

    /**
     *
     * @param planDrivage
     * 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(PlanDrivageReq planDrivage) {
        if (StrUtil.isBlank(planDrivage.getDrivagePlanId())){
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        PlanDrivage updateObj = new PlanDrivage();
        copyProperties(planDrivage, updateObj, planDrivage.getDrivagePlanType());
        updateObj.setDrivagePlanName(generatePlanName(planDrivage.getDrivagePlanType(),updateObj.getPlanStartDate()));
        updateObj.setDrivagePlanCode(generatePlanCode(planDrivage.getDrivagePlanType(),updateObj.getPlanStartDate()));
        QueryWrapper<PlanDrivage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("drivage_plan_code", updateObj.getDrivagePlanCode());
        queryWrapper.ne("drivage_plan_id", updateObj.getDrivagePlanId());
        queryWrapper.eq("drivage_face_id", updateObj.getDrivageFaceId());
        if (planDrivageMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一工作面和同一时段的计划");
        }
        int updateCount = planDrivageMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }

    /**
     *
     * @param id
     * 按主键id查询详情
     */
    @Override
    public PlanDrivageVO selectDetailById(String id) {
        PlanDrivage planDrivage = planDrivageMapper.selectById(id);
        if (planDrivage == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(planDrivage, PlanDrivageVO.class);
    }

    /**
     * 启用/禁用
     * @param id 数据id
     * @param status  status: 0:启用 1:禁用
     */
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            PlanDrivage planMining = planDrivageMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = planDrivageMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }

            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }
}
